package com.xnfh.equipment.viewmodel

import com.xnfh.common.bean.GateWayTotalInfoBean
import com.xnfh.common.bean.SfjOpenConfig
import com.xnfh.equipment.viewmodel.base.BaseTokenViewModel
import com.xnfh.framework.bean.RespStateData
import com.xnfh.framework.utils.JsonUtlis
import com.xnfh.network.constant.SFJ_NAME_V1
import org.json.JSONObject

/**
 * @Description:
 * @Author: ziheng
 * @CreateDate: 2023/12/25 14:58
 * @UpdateUser: ziheng
 * @UpdateDate: 2023/12/25 14:58
 * @UpdateRemark: 更新说明
 */
class KcEquipmentDetailViewModel : BaseTokenViewModel() {

    private val kcEquipmentDetailViewModelRes = KcEquipmentDetailViewModelRes()

    val KcDetailBean = RespStateData<GateWayTotalInfoBean>()
    val KcCloseOpenFm = RespStateData<Any>()


    /**
     * 获取设备的详情信息
     */
    fun requestKcDetail(gateWayId: String?) = launch {
        gateWayId?.let { kcEquipmentDetailViewModelRes.requestKcDetail(it, KcDetailBean) }
    }

    /**
     * @param gatewaytype 200表示新KC设备调用v2，13调用v1
     * @param gatewayid
     * @param deviceid
     * @param onOff
     * @param deviceIndex  V2 3-6使用搅拌开关、其他使用阀门开关
     * @param configData V2 搅拌开关使用到的参数
     * @return
     */
    fun openCloseFm(
        gatewaytype: Int,
        gatewayid: String?,
        deviceid: Int?,
        onOff: Int,
        deviceIndex: Int?,
        configData: String?
    ) = launch {
        val jsonObject = JSONObject()
        if (gatewaytype == 13) {
            jsonObject.put("username", SFJ_NAME_V1)
            jsonObject.put("gatewayid", gatewayid)
            jsonObject.put("deviceid", deviceid)
            jsonObject.put("onOff", onOff)
            jsonObject.put("runTime", 150)
            kcEquipmentDetailViewModelRes.requestColosOpenFm(creatRequestBody(jsonObject.toString()), KcCloseOpenFm)
        } else {
            jsonObject.put("gatewayId", gatewayid)
            jsonObject.put("deviceId", deviceid)
            jsonObject.put("deviceSwitch", onOff)
            if (deviceIndex in 3..6) {
                val fromJson = JsonUtlis.fromJson(configData, SfjOpenConfig::class.java)
                if (fromJson != null) {
                    jsonObject.put("singleRunTime", fromJson.singleRunTime)
                    jsonObject.put("degree", fromJson.residueDegree)
                    jsonObject.put("interval", fromJson.Interval)
                }
                kcEquipmentDetailViewModelRes.requestColosOpenJiaob(creatRequestBody(jsonObject.toString()), KcCloseOpenFm)
            } else {
                jsonObject.put("runTimes", 0)//接口文档 直接传0
                kcEquipmentDetailViewModelRes.requestColosOpenV2Fm(creatRequestBody(jsonObject.toString()), KcCloseOpenFm)
            }
        }
    }

}